/**
 * 
 */
package com.chh.mysso.client.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.chh.mysso.common.utils.CookieUtil;
import com.chh.mysso.common.utils.SSOConstant;
import com.chh.mysso.common.utils.SessionUtil;
import com.chh.mysso.domain.model.dto.AuthUserDTO;

/**
 * 登陆拦截器
 * 
 * @author chh
 *
 */
public class LoginInterceptor implements HandlerInterceptor {
	
	private final static String SSO_URL = "http://localhost/login";

	/*
	 * @see org.springframework.web.servlet.HandlerInterceptor#preHandle(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.Object)
	 */
	@Override
	public boolean preHandle(HttpServletRequest req, HttpServletResponse res, Object arg2) throws Exception {

		AuthUserDTO user = (AuthUserDTO) SessionUtil.getAttr(req, SSOConstant.LOGIN_USER);
		if (user != null) {
			return true;
		}
		String token = SessionUtil.getAttrString(req, SSOConstant.LOGIN_USER_SESSION_TOKEN);
		if (StringUtils.isBlank(token)) {
			token = CookieUtil.getCookieValue(req, SSOConstant.LOGIN_USER_SESSION_TOKEN);
			System.out.println(token);
			SessionUtil.put(req, SSOConstant.LOGIN_USER_SESSION_TOKEN, token);
		}
		if (StringUtils.isNoneBlank(token)) {
			// TODO 缓存中获取用户信息
			user = new AuthUserDTO();
		}
		String basePath = req.getScheme() + "://" + req.getContextPath() + "/" + req.getRequestURI();
		System.out.println(basePath);
		if (user == null) {
			res.sendRedirect(SSO_URL);
			return false;
		}
		SessionUtil.put(req, SSOConstant.LOGIN_USER, user);
		return true;
	}
	
	/*
	 * @see org.springframework.web.servlet.HandlerInterceptor#postHandle(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.Object, org.springframework.web.servlet.ModelAndView)
	 */
	@Override
	public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
			throws Exception {
	}
	
	/*
	 * @see org.springframework.web.servlet.HandlerInterceptor#afterCompletion(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.Object, java.lang.Exception)
	 */
	@Override
	public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
			throws Exception {
	}


}
